package com.cancer.biz.datasource;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;

/**
 * 数据源拦截器
 *
 * @company GeekPlus
 * @project beetle
 * @author 刘俊
 * @date Jun 15, 2017
 * @since 1.0.0
 */
public class DataSourceInterceptor implements IDataSourceInterceptor, Ordered {
	private static final Logger logger = LoggerFactory.getLogger(DataSourceInterceptor.class);
	// 默认拦截的方法
	private List<String> useSlaveDataSourceMethodPrefix = Arrays.asList("list", "query", "get", "select");

	@Override
//	@Around("execution(* com.geekplus.apollo.biz.report.service..*Service*.*(..))")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		// 切换数据源
		String method = point.getSignature().getName();
		boolean useSlave = useSlaveDataSourceMethodPrefix.stream().anyMatch(i -> method.startsWith(i));
		if (useSlave) {
			// 如果方法需要走从库，则切换当前线程的数据源
			logger.info("the method {} need switching datasource from {} to {}. method:{}", point.getSignature().getName(),
					DataSourceTypeManager.get(), DataSourceType.SLAVE, point.getSignature());
			DataSourceTypeManager.set(DataSourceType.SLAVE);
		}

		try {
			// 调用方法
			Object res = point.proceed();
			return res;
		} finally {
			// 执行完毕后再切回主库
			if (DataSourceTypeManager.get() == DataSourceType.SLAVE) {
				logger.info("the method {} finished and now switching datasource from {} to {} ",
						point.getSignature().getName(), DataSourceTypeManager.get(), DataSourceType.MASTER);
				DataSourceTypeManager.set(DataSourceType.MASTER);
			}
		}
	}

//	@Before("execution(* com.geekplus.apollo.biz.report.service..*Service*.*(..))")
//	@Override
//	public void before(JoinPoint point) {
//		// 切换数据源
//		String method = point.getSignature().getName();
//		boolean useSlave = useSlaveDataSourceMethodPrefix.stream().anyMatch(i -> method.startsWith(i));
//		if (useSlave) {
//			// 如果方法需要走从库，则切换当前线程的数据源
//			logger.info("the method {} need switching datasource from {} to {}. method:{}", point.getSignature().getName(),
//					DataSourceTypeManager.get(), DataSourceType.SLAVE, point.getSignature());
//			DataSourceTypeManager.set(DataSourceType.SLAVE);
//		}
//	}

//	@After("execution(* com.geekplus.apollo.biz.report.service..*Service*.*(..))")
//	@Override
//	public void after(JoinPoint point) {
//		// 执行完毕后再切回主库
//		if (DataSourceTypeManager.get() == DataSourceType.SLAVE) {
//			logger.info("the method {} finished and now switching datasource from {} to {} ", point.getSignature().getName(), DataSourceTypeManager.get(), DataSourceType.MASTER);
//			DataSourceTypeManager.set(DataSourceType.MASTER);
//		}
//	}

	public void setUseSlaveDataSourceMethodPrefix(List<String> useSlaveDataSourceMethodPrefix) {
		this.useSlaveDataSourceMethodPrefix = useSlaveDataSourceMethodPrefix;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1; // 优先级要高高高高高
	}

}
